package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.config.security.JwtTokenUtils;
import com.xxxx.server.mapper.AdminMapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.util.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wyd
 * @since 2023-06-11
 */
@Service
@Slf4j(topic = "AdminServiceImpl")
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 登录功能
     *
     * @param code
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public RespBean login(String code, String username, String password, HttpServletRequest request) {

        //从session中拿到验证码
        String captcha = (String) request.getSession().getAttribute("captcha");

        log.info("从session中拿到验证码:{}",captcha);

        log.info("用户输入的code:{}",code);

        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){

           return RespBean.error("验证码输入错误!");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        if (null == userDetails || !passwordEncoder.matches(password,userDetails.getPassword())){

            return RespBean.error("用户名或密码不正确!");

        }

        if (!userDetails.isEnabled()){

            return RespBean.error("账号被禁用，请联系管理员!");
        }

        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails,
                null,
                userDetails.getAuthorities()
        );

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtils.generateToken(userDetails);

        Map<String,String> tokenMap = new HashMap<>();

        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);


        return RespBean.success("登录成功",tokenMap);
    }

    /**
     * 查询Admin
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUsername(String username) {

        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Admin::getUsername,username);
        queryWrapper.eq(Admin::getEnabled,true);

        Admin admin = adminMapper.selectOne(queryWrapper);

        return admin;
    }

    @Override
    public List<Role> getRoles(Integer adminId) {

        return roleMapper.getRoles(adminId);
    }


}
